package com.xmutca.micro.gateway.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.AbstractErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class GlobalErrorController extends AbstractErrorController implements ErrorController {

    @Value("${error.path:/error}")
    private String errorPath;

    public GlobalErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping("${error.path:/error}")
    public ResponseEntity error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status.is5xxServerError()) {
            // log maybe
            System.out.println(status.getReasonPhrase());
        }

        if (status.is4xxClientError()) {
            System.out.println(status.getReasonPhrase());
        }
        return new ResponseEntity(status);
    }

    @Override
    public String getErrorPath() {
        return errorPath;
    }
}